package com.link.base.tencent.corpwx.media.service;

import com.link.base.base.common.dao.mybatis.mapper.AttachmentMapper;
import com.link.base.base.common.model.Attachment;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.media.dao.mybatis.mapper.CorpWxMediaMapper;
import com.link.base.tencent.corpwx.media.model.CorpWxMedia;
import com.link.base.tencent.corpwx.media.util.MediaUtil;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.modules.export.FileIndexGenarate;
import com.link.core.util.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 企业微信素材管理
 *
 * @author liozongting
 * @date 2019/1/26
 */
@Service
public class CorpWxMediaServiceImpl extends BasicServiceImpl<CorpWxMedia> implements CorpWxMediaService {

    @Resource
    private AgentService agentService;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private CorpWxMediaMapper corpWxMediaMapper;
    @Resource
    private AttachmentMapper attachmentMapper;

    @Override
    public BasicMapper<CorpWxMedia> getBasicMapper() {
        return corpWxMediaMapper;
    }

    @Override
    public CorpWxMedia downloadMedia(CorpWxMedia record) throws Exception {
        Long headId = record.getHeadId();
        if (headId == null) {
            throw new BasicServiceException("parentId不能为空！");
        }
        if (StringUtils.isBlank(record.getAgentId())) {
            throw new BasicServiceException("agentId不能为空！");
        }
        if (StringUtils.isBlank(record.getMediaId())) {
            throw new BasicServiceException("mediaId不能为空！");
        }
        if (StringUtils.isNull(record.getModuleType())) {
            record.setModuleType("other");
        }
        String accessToken = agentService.getExistAccessToken(record.getAgentId());
        record = MediaUtil.downloadMedia(accessToken, record.getMediaId(), record.getModuleType());
        record.setHeadId(headId);
        record.setId(keyGenerateService.keyGenerate());
        corpWxMediaMapper.attachmentInsert(record);
        record = corpWxMediaMapper.queryAttachmentById(record);
        return record;
    }

    @Override
    public CorpWxMedia uploadMediaToWx(String agentId, String type, File file) throws Exception {
        if (StringUtils.isBlank(type)) {
            throw new BasicServiceException("素材类型type不能为空！");
        }
        if (StringUtils.isBlank(agentId)) {
            throw new BasicServiceException("agentId不能为空！");
        }
        // 获取接口调用凭证
        String accessToken = agentService.getExistAccessToken(agentId);
        // 调用素材上传方法
        return  MediaUtil.uploadMedia(accessToken, type, file);
    }

    @Override
    public CorpWxMedia uploadMedia(HttpServletRequest request, CorpWxMedia record) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        MultipartFile media = multipartRequest.getFile("uploadAttachment");
        if (media == null || media.isEmpty()) {
            throw new BasicServiceException("上传素材内容为空");
        }
        // 附件存放的绝对路径
        String pathFolder = YmlConstants.getPortalShareFileDir() + "/CorpWx/";
        // 素材的名称
        String originalFilename = media.getOriginalFilename();
        // 生成素材的名称
        SimpleDateFormat datetimeFormatter = new SimpleDateFormat("yyyyMMddHHmmsss");
        String fileName = datetimeFormatter.format(new Date()) + "_" + FileIndexGenarate.getFileIndex(new Date())
                + originalFilename.substring(originalFilename.lastIndexOf('.'));
        //附件存放的相对路径
        String relativePath = "/CorpWx/" + fileName;
        // 获取素材的后缀名获取素材的类型
        Attachment attachment = new Attachment();
        Long attachmentId = keyGenerateService.keyGenerate();
        attachment.setId(attachmentId);
        attachment.setAttachmentName(fileName);
        attachment.setAttachmentPath(relativePath);
        attachment.setAttachmentOriginal(originalFilename);
        attachment.setAttachmentSize(String.valueOf(media.getSize()));
        attachment.setAttachmentType(record.getMediaType());
        // 存储文件到服务器
        File fileObj = new File(pathFolder, fileName);
        FileUtils.copyInputStreamToFile(media.getInputStream(), fileObj);
        attachmentMapper.insert(attachment);
        // 上传素材到企业微信服务器
        CorpWxMedia entity = this.uploadMediaToWx(AgentIdUtil.CORPWX_ACCOUNT_AGENTID, record.getMediaType(), fileObj);
        entity.setAttachmentId(attachmentId);
        entity.setModuleType(record.getModuleType());
        entity.setMediaType(record.getMediaType());
        entity.setMediaName(originalFilename);
        insert(entity);
        return entity;
    }


    /** 
    * 根据文件后缀命获取文件类型
    * @author Lizongting
    * @date 2020/1/16
    */ 
    public static String getFileType(String fileName) {
        String fileSuffix = fileName.substring(fileName.lastIndexOf('.') + 1);
        String fileType = "";
        if (StringUtils.isNotBlank(fileSuffix)) {
            fileSuffix = fileSuffix.toLowerCase();
        }
        switch (fileSuffix) {
            case "jpg": case "png": case "bmp":
                fileType = "image";
                break;
            case "amr":
                fileType = "voice";
                break;
            case "mp4":
                fileType = "video";
                break;
            default:
                fileType = "file";
        }
        return fileType;
    }
}
